import 'package:lcapp/model/db/sql_constant.dart';
import 'package:lcapp/model/db/sqlite.dart';
import 'package:lcapp/tools/map_tool.dart';
import 'package:sqflite/sqflite.dart';

class SearchHistoryDB {
  static Future<bool> deleteRecord(int id) async{
    Database database =
    await SqliteSingleton.getInstance().getUserDB();
    int results = await database.rawDelete('DELETE FROM "$TB_SEARCH_HISTORY" WHERE id = ? ',[id]);

    return results!=null&&results>0?true:false;
  }
  //删除一组历史记录
  static Future<bool> deleteGroupRecord(String module) async{

    Database database =
    await SqliteSingleton.getInstance().getUserDB();
    int results = await database.rawDelete('DELETE FROM "$TB_SEARCH_HISTORY" WHERE module = ? ',[module]);

    return results!=null&&results>0?true:false;
  }

  //根据要求插入搜索历史记录
  static Future<void> operateRecord(Map data) async{
    Database database =
    await SqliteSingleton.getInstance().getUserDB();
    List results = await database.rawQuery(
        'SELECT * ' +
            'FROM  $TB_SEARCH_HISTORY  ' +
            'WHERE module = ? AND record = ?',
        [data["module"],data["record"]]);
    if(!(results!=null&&results.length>0)){
      List countResults = await database.rawQuery(
          'SELECT COUNT(*) AS count ' +
              'FROM  $TB_SEARCH_HISTORY  ' +
              'WHERE module = ?',
          [data["module"]]);
      if(countResults!=null&&countResults.length>0&&countResults[0]["count"] > 9){
        int delResults = await database.rawDelete('DELETE FROM "$TB_SEARCH_HISTORY" WHERE id = ( SELECT MIN(id) FROM  "$TB_SEARCH_HISTORY")');
      }
      int results = await database.insert(TB_SEARCH_HISTORY, MapTool.camel2under(data));
    }
  }
  //获取搜索结果
  static Future<List> getHistory(String module) async{
    Database database =
    await SqliteSingleton.getInstance().getUserDB();
    List results = await database.rawQuery(
        'SELECT * ' +
            'FROM  $TB_SEARCH_HISTORY  ' +
            'WHERE module = ? ORDER BY id DESC LIMIT 10',
        [module]);
    return results;
  }
}